package com.ly.hotel.timetask;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;
import java.util.Random;
import java.util.TimerTask;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ly.hotel.R;
import com.ly.hotel.adaptor.HardwareInterface;
import com.ly.hotel.adaptor.NetworkUtil;
import com.ly.hotel.common.Constants;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.SharedPreferencesConfig;
import com.ly.hotel.model.ModelBean;
import com.ly.hotel.model.Soft;
import com.ly.hotel.model.Vodvideo;
import com.ly.hotel.msgevent.GetVodVideoEvent;
import com.ly.hotel.service.SPABackService;
import com.ly.hotel.service.SPAService;
import com.ly.hotel.util.AppUtil;
import com.ly.hotel.util.FileUtils;
import com.ly.hotel.view.fragments.vod.NativeVideoPlayerActivity;
import com.ly.hotel.view.setting.SystemUpdateDeviceInfo;

import de.greenrobot.event.EventBus;

import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

public class MyCmdTimerTask extends TimerTask{
	private ThisHandler handler = new ThisHandler(this);
	private static final Gson gson = new GsonBuilder().create();
	private static final int CMD_STATE_FAIL = 0;
	private static final int CMD_STATE_SUCCESS = 1;
	private static final int CMD_STATE_NEED_REBOOT = 2;
	private static final int CMD_STATE_NEED_UPDATE = 3;
	private static final int CMD_STATE_NEED_RESTART_APP = 4;
	@Override
	public void run() {
		// TODO Auto-generated method stub
		Message message = new Message();
        message.what=1;
        handler.sendMessage(message);
	}

	private static class ThisHandler extends Handler {
		private WeakReference<MyCmdTimerTask> wrActivity;

		public ThisHandler(MyCmdTimerTask activity) {
			wrActivity = new WeakReference<MyCmdTimerTask>(activity);
		}

		@Override
		public void handleMessage(Message message) {
			super.handleMessage(message);
            if(message.what==1) {
            	String url = MyApplication.getHost() + SPAService.PROJECT + "/api/getcmd.json?mac=" + MyApplication.getMAC();


				StringRequest  stringRequest = new StringRequest(Request.Method.GET, url, 
		                 new Response.Listener<String>() {  
		                     @Override  
		                     public void onResponse(String response) {  
		             			Boolean needReboot = false;
		            			Boolean needUpdate = false;
		            			Boolean resetApp = false;
		            			String ackCmd = "";
		                    	String result = response;
		         				
		         				ModelBean d1 = gson.fromJson(result, ModelBean.class);

		         				if (d1.getCode().equals(-1) || d1.getData() == null || d1.getData().equals("")){
		         					
		         					return;
		         				}
		         				String str = d1.getData().toString().replace(" ", "");
		         				
//		         				Log.i("rtmsg", "实时消息获取成功:" + str);
		         				
		         				if (!(str == null || str.equals("null"))) {
		         					ackCmd = "";
		         					Log.i("cmd", "命令串:" + str);
//		         					lastCmd = str;
		         					String[] cmdList = str.split(";");

		         					for (String c : cmdList) {
		         						
		         						switch (processCmd(c)) {
		         							case CMD_STATE_FAIL:
		         								ackCmd = ackCmd + "失败_" + c + ";";
		         								break;
		         							case CMD_STATE_SUCCESS:
		         								ackCmd = ackCmd + "成功_" + c + ";";
		         								break;
		         							case CMD_STATE_NEED_REBOOT:
		         								ackCmd = ackCmd + "成功_" + c + ";";
		         								needReboot = true;
		         								break;
		         							case CMD_STATE_NEED_UPDATE:
		         								ackCmd = ackCmd + "成功_" + c + ";";
		         								needUpdate = true;
		         								break;
		         							case CMD_STATE_NEED_RESTART_APP:
		         								ackCmd = ackCmd + "成功_" + c + ";";
		         								resetApp = true;
		         								break;
		         						}

		         						// Log.i("cmd", "执行完成的命令:" + ackCmd);
         								String name = MyApplication.getDeviceInfo()
         										.getCategoryName() + "-" + MyApplication.getDeviceInfo().getName() + ",";
         								String mac = MyApplication.getMAC();
         								String ack = ackCmd;
         								// 通过自己的ID获取子列表
         								final String url1 = MyApplication.getHost() + SPAService.PROJECT + "/api/ackcmd.json?mac=" + name + mac + "&cmd=" + ack;
         								StringRequest  stringRequest = new StringRequest(Request.Method.GET, url1, 
         						                 new Response.Listener<String>() {  
         						                     @Override  
         						                     public void onResponse(String response) {  
         						                    	 Log.i("heart", "推送命令运行完成:" + response);
         						                     }  
         						                 }, new Response.ErrorListener() {  
         						                     @Override  
         						                     public void onErrorResponse(VolleyError error) {  
         						                    	 Log.e("heart", "推送命令失败." + error.getMessage()); 
         						                     }  
         						                 }); 
         								stringRequest.setTag("cmd");
         								stringRequest.setShouldCache(false);
         								SPABackService.mQueue.add(stringRequest);

		         						if (needReboot) {
		         							Log.i("updata", "重启系统.");
		         							MyApplication.rebootSystemDelay(3000);
		         						} else if (needUpdate) {

		         							Log.i("updata", "检测是否需要升级.");
		         							needUpdate = false;
		         							int version = AppUtil.getVersion(MyApplication.getContext(), MyApplication.getContext().getPackageName());
		         							String versionName = AppUtil.getVersionName(MyApplication.getContext(), MyApplication.getContext().getPackageName());//主版本号
		         							Soft soft = SPAService.checkSoftUpdate(MyApplication.getMAC() ,versionName, version);
		         							
		         							if (soft != null) {
		         								Log.i("updata","当前版本:" + version + "服务器升级文件版本:" + soft.getVersion());
		         								
		         								if (version < soft.getVersion()) {
		         									//通过重启来更新
		         									MyApplication.rebootSystemDelay(3000);
		         								}
		         							}else{
		         								Log.i("updata", "没有升级信息");
		         							}

		         						}else if(resetApp){
		         							Resources resources = MyApplication.getContext().getResources();// 获得res资源对象
		         							Configuration config = resources.getConfiguration();// 获得设置对象
		         							Log.i("InitActivity", "系统语言设置完成:"+config.locale.toString());
		         							
		         							/*还需要把设置配置到系统语言才能生效*/
		         							
		         							/**/
		         							SharedPreferencesConfig.setLanguage(MyApplication.getContext(), config.locale.toString());
		         							Intent i = new Intent("com.ly.sap.language");
		         							MyApplication.getContext().sendBroadcast(i);
		         						}
		         					}
		         				}
		                     }  
		                 }, new Response.ErrorListener() {  
		                     @Override  
		                     public void onErrorResponse(VolleyError error) {  
		                    	 
		                     }  
		                 }); 
				stringRequest.setTag("cmd");
				stringRequest.setShouldCache(false);
				SPABackService.mQueue.add(stringRequest);
            }
		}
	}
	
	public static void switchLanguage(Locale locale) {
		Resources resources = MyApplication.getContext().getResources();// 获得res资源对象
		Configuration config = resources.getConfiguration();// 获得设置对象
		DisplayMetrics dm = resources.getDisplayMetrics();// 获得屏幕参数：主要是分辨率，像素等。
		config.locale = locale; // 简体中文
		resources.updateConfiguration(config, dm);
	}
	
	private static int processCmd(String str) {
		String cmds[] = str.split(",");
		String cmd=null;
		
		if(cmds.length >= 1){
			cmd = cmds[0];
		}else{
			Log.e("cmd", "命令出错:" + str);
		}
		
		int rv = CMD_STATE_FAIL;
		Log.i("cmd", "处理命令:" + cmd);
		if (cmd.equals("setSpaServerIp")) {
			String ip = cmds[1];

			SharedPreferencesConfig.setSpaServer(MyApplication.getContext(), ip);
			MyApplication.setHost(SharedPreferencesConfig.getSpaServer(MyApplication.getContext()));
			Log.i("cmd", "设置IP成功:" + MyApplication.getHost());
			rv = CMD_STATE_SUCCESS;
		} else if (cmd.equals("reboot")) {
			Log.i("cmd", "重启系统");
			rv = CMD_STATE_NEED_REBOOT;
		} else if (cmd.equals("baud")) {
			String baud = cmds[1];
			Integer b = Integer.parseInt(baud);
			if (b == 9600 || b == 19200 || b == 38400 || b == 115200) {
				SharedPreferencesConfig.setSerialBaud(MyApplication.getContext(), b);
				if (SharedPreferencesConfig.getSerialBaud(MyApplication.getContext()) == b) {
					Log.i("cmd", "设置波特率:" + baud);
					rv = CMD_STATE_SUCCESS;
				}
			} else {
				Log.i("cmd", "波特率参数失败");
				rv = CMD_STATE_FAIL;
			}
		} else if (cmd.equals("update")) {
			Log.i("cmd", "立即更新系统");
			rv = CMD_STATE_NEED_UPDATE;
		} else if (cmd.equals("volume")) {
			String volume = cmds[1];
			Integer b = Integer.parseInt(volume);
			if (b >= 0 && b <= 100) {
				HardwareInterface.setMaxVolume(b);
				rv = CMD_STATE_SUCCESS;
			}
			rv = CMD_STATE_FAIL;
		} else if (cmd.equals("vodInit")) {
//			initVodVideo(1);//0是历史
			EventBus.getDefault().post(new GetVodVideoEvent(MyApplication.getVodpart().get(1)));
			rv = CMD_STATE_SUCCESS;
		} else if (cmd.equals("vodTest")) {
			Log.i("cmd", "测试视频播放");
			if (MyApplication.getVodpart() != null && MyApplication.getVodpart().size() > 0 && MyApplication.getVodpart().get(1) != null
					&& MyApplication.getVodpart().get(1).getVodvideoBeanList() != null
					&& MyApplication.getVodpart().get(1).getVodvideoBeanList().get(0) != null
					&& MyApplication.getVodpart().get(1).getVodvideoBeanList().get(0).getMovies() != null
					&& MyApplication.getVodpart().get(1).getVodvideoBeanList().get(0).getMovies().get(0) != null) {

				Random random = new Random();
				int index = Math.abs(random.nextInt())
						% (MyApplication.getVodpart().get(1).getVodvideoBeanList().get(0).getMovies().size());

				Vodvideo v = MyApplication.getVodpart().get(1).getVodvideoBeanList().get(0).getMovies().get(index);
				String url = v.getPath();
				Log.i("cmd", "将要播放" + v.getName());
				if (url != null) {
					url = MyApplication.getHostResUrl() + url;
					Log.i("cmd", v.getName() + " url=" + url);

					Intent intent = new Intent(MyApplication.getContext(), NativeVideoPlayerActivity.class);
					intent.putExtra("path", url);
					intent.putExtra("filmName", v.getName());
					intent.putExtra("filmId", v.getId());
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					MyApplication.getContext().startActivity(intent);

					MyApplication.isLoopPlay = true;

					rv = CMD_STATE_SUCCESS;
				}
			}
		} else if (cmd.equals("stopVodTest")) {
			MyApplication.isLoopPlay = false;
			rv = CMD_STATE_SUCCESS;
		} else if (cmd.equals("screenSize")) {
			String size = cmds[1];

			SharedPreferencesConfig.setScreenSize(MyApplication.getContext(), size);
			if(SharedPreferencesConfig.getScreenSize(MyApplication.getContext()).equals(size)){
				Log.i("cmd", "设置屏幕大小成功:" + size);
				rv = CMD_STATE_SUCCESS;
			}else{
				Log.i("cmd", "设置屏幕大小失败:" + size);
				rv = CMD_STATE_FAIL;
			}
		} else if (cmd.equals("updateIPTVApk")){
			File file = new File(Constants.CUSTOM_TV_APK_ROOT + "/" + Constants.CUSTOM_TV_APK_FILE_NAME);
			if(file.exists()){
				file.delete();
			}
			
			rv = CMD_STATE_SUCCESS;
		} else if (cmd.equals("set628PlayerOn")){
			MyApplication.ada628Player = true;
			rv = CMD_STATE_SUCCESS;
		} else if (cmd.equals("set628PlayerOff")){
			MyApplication.ada628Player = false;
			rv = CMD_STATE_SUCCESS;
		} else if(cmd.equals("lang")){
			
			if(cmds[1].equals("en-us")){
				Log.i("cmd", "设置语言为英文");
				switchLanguage(Locale.ENGLISH);
				rv = CMD_STATE_NEED_RESTART_APP;
			}else if(cmds[1].equals("zh-cn")){
				Log.i("cmd", "设置语言为中文");
				switchLanguage(Locale.SIMPLIFIED_CHINESE);
				rv = CMD_STATE_NEED_RESTART_APP;
			}else{
				Log.i("cmd", "参数无法识别:"+cmds[1]);
				rv = CMD_STATE_FAIL;
			}

		}else if (cmd.equals("updateNetInfo")){
			
			/*读取网络文件*/
//			File file = new File(MyApplication.getHostIpAndPort(this) + "/upload/TvConf.txt");// Text文件
			final String urlStr = "http://" + MyApplication.getHostIpAndPort() + "/upload/TvConf.txt";
				
				// 取得inputStream，并进行读取
				new Thread(){
					@Override
					public void run(){
						try{
							String ip = null;
							String gateway = null;
							String mask = null;
							String dns = null;
							String dns2 = null;
							String info[];
							URL url = new URL(urlStr);
							
							HttpURLConnection conn = (HttpURLConnection) url.openConnection();
							conn.setConnectTimeout(60 * 1000);
							conn.setReadTimeout(60 * 1000);
							InputStream input = conn.getInputStream();
							BufferedReader in = new BufferedReader(new InputStreamReader(input));
							
							String line = null;
							Log.i("cmd", "mac=" + MyApplication.getMAC().toUpperCase(Locale.US));
							
							while ((line = in.readLine()) != null) {
								Log.i("cmd", "读取：" + line);
								if (line.contains(MyApplication.getMAC().toUpperCase(Locale.US))) {
									Log.e("cmd", "匹配：" + line);
									
									info = line.split("-");
									
									if(NetworkUtil.isIpAddr(info[3]))
										ip = info[3];
									
									if(NetworkUtil.isIpAddr(info[4]))
										gateway = info[4];
									
									if(NetworkUtil.isIpAddr(info[5]))
										mask = info[5];
									
									if(NetworkUtil.isIpAddr(info[6]))
										dns = info[6];
									
									if(NetworkUtil.isIpAddr(info[7]))
										dns2 = info[7];
									
									if(ip != null || mask != null || gateway != null || dns != null || dns2 != null){
//										NetworkUtil.setNetWorkInfo(MyApplication.getContext(), ip, gateway, mask, dns, dns2);
										Log.i("cmd", "设置网络->" + ip + " " + gateway + " " + mask + " " + dns + " " + dns2 + " ");
										if(NetworkUtil.isConnected(MyApplication.getContext())){
											HardwareInterface.rebootSystem();
										}
									}
									
									in.close();
									break;
								}
								
							}
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}.start();
			
		}  else if (cmd.equals("debug")) {
			String mode = cmds[1];

			SharedPreferencesConfig.setDebug(MyApplication.getContext(), mode);
			Log.i("cmd", "设置调试模式:" + SharedPreferencesConfig.getDebug(MyApplication.getContext()));
			rv = CMD_STATE_SUCCESS;
		} else if (cmd.equals("deleteTvList")) {
			
			FileUtils.deleteFile(new File("/data/data/com.ly.hotel/files/list"));
			FileUtils.deleteFile(new File("/data/openfiles2share/TvChannel"));
			FileUtils.deleteFile(new File(Constants.SPA_TV_LIST_FILE_PATH));
			
			rv = CMD_STATE_SUCCESS;
		} else if (cmd.equals("setMovieEnable")) {
			/*用于分区域禁止播放电影*/
			String mode = cmds[1];
			boolean enable = true;
			if(mode.equals("OFF")){
				enable = false;
			}
			SharedPreferencesConfig.setMovieEnable(MyApplication.getContext(), enable);
			rv = CMD_STATE_SUCCESS;
		} else if(cmd.equals("factorySetting")){
			SystemUpdateDeviceInfo dialog = new SystemUpdateDeviceInfo(MyApplication.getContext(), R.style.InputDialog);// 创建Dialog并设置样式主题
			dialog.setCanceledOnTouchOutside(false);
			dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
			dialog.show();
			rv = CMD_STATE_SUCCESS;
		}

		return rv;
	}
}
